﻿using System;
using System.Linq;
using System.Web.Mvc;
using EPiServer.Common.Categories;
using JoelAbrahamsson.BlogExtensions;

namespace JoelAbrahamsson.Web.ModelBinders
{
    public class CategoryModelBinder : IModelBinder
    {
        private BlogCategoryProvider _blogCategoryProvider;

        public CategoryModelBinder (BlogCategoryProvider blogCategoryProvider)
        {
            _blogCategoryProvider = blogCategoryProvider;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string mainCategoryName = ParseSlug(controllerContext.RouteData.Values["mainCategoryName"].ToString());
            string subCategoryName = ParseSlug(controllerContext.RouteData.Values["subCategoryName"].ToString());

            ICategory mainCategory = _blogCategoryProvider.BlogCategoriesRoot.Children
                .Where(category => category.Name.Equals(mainCategoryName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            ICategory subCategory = mainCategory.Children
                .Where(category => category.Name.Equals(subCategoryName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            return subCategory;
        }

        private string ParseSlug(string slug)
        {
            return slug
                .Replace("-", " ")
                .Replace("sharp", "#");
        }
    }
}
